#!/usr/bin/python

from distutils.core import setup
from glob import glob
import os, sys, re
from yapget import yapget_version
from yapgui import gui_version

def get_svn_revision():
	"""
	Returns the SVN revision in the form SVN-XXXX,
	where XXXX is the revision number.

	Returns SVN-unknown if anything goes wrong, such as an unexpected
	format of internal SVN files.
	"""
	rev = None
	entries_path = '%s/.svn/entries' % '.'

	if os.path.exists(entries_path):
		entries = open(entries_path, 'r').read()
		# Versions >= 7 of the entries file are flat text.  The first line is
		# the version number. The next set of digits after 'dir' is the revision.
		if re.match('(\d+)', entries):
			rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
			if rev_match:
				rev = rev_match.groups()[0]
		# Older XML versions of the file specify revision as an attribute of
		# the first entries node.
		else:
			from xml.dom import minidom
			dom = minidom.parse(entries_path)
			rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')

	if rev:
		return 'SVN-%s' % rev
	return 'SVN-unknown'

def TixInfo():
	import Tkinter
	import _tkinter

	tk = _tkinter.create()

	tcl_version = _tkinter.TCL_VERSION
	tk_version = _tkinter.TK_VERSION
	tix_version = tk.call("package", "version", "Tix")

	tcl_dir = tk.call("info", "library")

	del tk, _tkinter, Tkinter

	return (tcl_version, tk_version, tix_version, tcl_dir)

class RecursiveFileIterator:
	# Great script from Daniel Dittmar,
	# http://www.faqts.com/knowledge-base/view.phtml/aid/6000
	def __init__(self, *rootDirs):
		self.dirQueue = list(rootDirs)
		self.includeDirs = None
		self.fileQueue = []

	def __getitem__(self, index):
		while len(self.fileQueue) == 0:
			self.nextDir()
		result = self.fileQueue[0]
		del self.fileQueue[0]
		return result

	def nextDir(self):
		dir = self.dirQueue[0]	# fails with IndexError, which is fine
					# for iterator interface
		del self.dirQueue[0]
		list = os.listdir(dir)
		join = os.path.join
		isdir = os.path.isdir
		for basename in list:
			fullPath = join(dir, basename)
			if isdir (fullPath):
				self.dirQueue.append(fullPath)
				if self.includeDirs:
					self.fileQueue.append(fullPath)
			else:
				self.fileQueue.append(fullPath)

try:
	import py2exe
	from py2exe.build_exe import py2exe as BuildExe

	class myPy2Exe(BuildExe):
		def plat_finalize(self, modules, py_files, extensions, dlls):
			BuildExe.plat_finalize(self, modules, py_files, extensions, dlls)

			if "Tix" in modules:
				# Tix adjustments
				tcl_version, tk_version, tix_version, tcl_dir = TixInfo()

				tcl_src_dir = os.path.split(tcl_dir)[0]

				tixdll = "tix%s%s.dll" % (tix_version.replace(".", ""),
						tcl_version.replace(".", ""))
				tcldll = "tcl%s.dll" % tcl_version.replace(".", "")
				tkdll = "tk%s.dll" % tk_version.replace(".", "")

				tix_path = os.path.join(sys.prefix, "DLLs")
				if not os.path.isfile(os.path.join(tix_path, tixdll)):
					tixdll = "tix%s.dll" % tix_version.replace(".", "")
					tix_path = os.path.join(sys.prefix, tcl_src_dir, "tix%s" % tix_version)
					if not os.path.isfile(os.path.join(tix_path, tixdll)):
						print "Unable to find Tix dll"
						sys.exit(1)

				dlls.add(os.path.join(tix_path, tixdll))

				self.dlls_in_exedir.extend( [tcldll, tkdll, tixdll ] )

				tcl_dst_dir = os.path.join(self.lib_dir, "tcl")
				self.announce("Copying TIX files from %s..." % tcl_src_dir)
				self.copy_tree(os.path.join(tcl_src_dir, "tix%s" % tix_version),
						os.path.join(tcl_dst_dir, "tix%s" % tix_version))
except: pass

author='Yan Burman'
author_email='burman.yan@gmail.com'
description='Application for batch downloading files from number of supported sites'
url='http://code.google.com/p/yapget/'
license='LGPL'

if __name__ == '__main__':
	if 'py2exe' in dir():
		import zipfile

		options = {"py2exe": {"compressed": 0, "optimize": 1, "bundle_files": 1} }

		f = os.popen('python -O yapget.py')
		data = f.read()
		del data

		setup(
			name='yapget' + '-' + yapget_version + '-' + get_svn_revision(),
			version=yapget_version,
			author=author,
			author_email=author_email,
			description=description,
			url=url,
			license=license,
			options=options,
			zipfile=None,
			console=['yapget.py'],
			)

		setup(
			name='YapGUI' + '-' + gui_version + '-' + get_svn_revision(),
			version=gui_version,
			author=author,
			author_email=author_email,
			description=description,
			url=url,
			license=license,
			script_args=['py2exe'],
			zipfile=None,
			cmdclass={'py2exe': myPy2Exe},
			windows=['yapgui.pyw'],
			options=options,
			data_files=[
				('plugins', glob(os.path.join('plugins', '*.pyo'))),
				('', ['license.txt']),
				],
			)
		dist_directory = 'yapget-' + yapget_version + '-' + get_svn_revision()
		os.rename('dist', dist_directory)
		f = zipfile.ZipFile(dist_directory + '.zip', 'w')
		for name in RecursiveFileIterator(dist_directory):
			if os.path.isfile(name):
				f.write(name, name, zipfile.ZIP_DEFLATED)
		f.close()
	else:
		setup(
			name='yapget' + '-' + yapget_version + '-' + get_svn_revision(),
			version=yapget_version,
			author=author,
			author_email=author_email,
			description=description,
			url=url,
			license=license,
			scripts=[
				'yapget.py',
				'rarfile.py',
				'Meter.py',
				'yapgui.pyw',
				],
			data_files=[
				('yapget/plugins', glob(os.path.join('plugins', '*.py'))),
				('yapget', ['license.txt']),
				],
			)

